import axios from 'axios'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import router from '@/router'
const baseURL = 'http://192.168.70.141:8500'

const instance = axios.create({
  // 基础地址
  baseURL,
  timeout: 5000
})

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    const useStore = useUserStore()
    if (useStore.token) {
      config.headers.token = useStore.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

//响应拦截器
instance.interceptors.response.use(
  (res) => {
    if (res.data.code === 0 || res.data.code === 200) {
      return res
    } else if (res.data.code === 208) {
      const useStore = useUserStore()
      useStore.removeToken()
      router.push('/login')
    }
    // 处理失败
    ElMessage.error(res.data.message || '服务异常')
    return Promise.reject(res.data)
  },
  (err) => {
    //特殊情况 401权限不足 或 token过期 => 拦截到登录
    if (err.response?.status === 401) {
      router.push('/login')
    }
    //默认错误情况
    ElMessage.error(err.response.data.message || '服务异常')
    return Promise.reject(err)
  }
)

export default instance
export { baseURL }
